package com.ship.dispatch.service.fob.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ship.dispatch.bean.SmShipFreightCost;
import com.ship.dispatch.bean.SpDispatchSchemeExecute;
import com.ship.dispatch.bean.fob.*;
import com.ship.dispatch.bpm.service.TaskService;
import com.ship.dispatch.bpm.utils.JsonUtils;
import com.ship.dispatch.bpm.vo.ManageEntityVo;
import com.ship.dispatch.mapper.fob.SpfobJsfhccbMapper;
import com.ship.dispatch.mapper.fob.SpfobUpjsfhccbMapper;
import com.ship.dispatch.service.SmShipFreightCostService;
import com.ship.dispatch.service.SpDispatchSchemeExecuteService;
import com.ship.dispatch.service.fob.SpFobFileRecordService;
import com.ship.dispatch.service.fob.SpfobJsfhccbService;
import com.ship.dispatch.service.fob.SpfobUpjsfhccbService;
import com.ship.dispatch.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author yl
 * @title SpfobJsfhccbServiceImpl
 * @description 计算往返航次成本用于报关
 * @create 2023/12/18 0018
 */
@Service
public class SpfobUpjsfhccbServiceImpl extends FobBaseServiceImpl<SpfobUpjsfhccbMapper, SpfobUpjsfhccb> implements SpfobUpjsfhccbService {

    @Autowired(required = false)
    SpfobUpjsfhccbMapper spFobGmbxMapper;

    @Autowired
    SpFobFileRecordService spFobFileRecordService;


    @Autowired
    SpDispatchSchemeExecuteService dispatchSchemeExecuteService;

    @Autowired
    SpfobJsfhccbService spfobJsfhccbService;

    @Autowired
    TaskService taskService;

    @Override
    public void updateEntity(ManageEntityVo manageEntityVo, String json) {
        SpfobUpjsfhccb object = JsonUtils.jsonToObject(json,SpfobUpjsfhccb.class);
        SpfobUpjsfhccb his = spFobGmbxMapper.selectOne(new LambdaQueryWrapper<SpfobUpjsfhccb>().eq(SpfobUpjsfhccb::getProceeInstanceId,manageEntityVo.getProcessInstanceId()).ne(SpfobUpjsfhccb::getStatus,-2));
        if(manageEntityVo.getOperationType()==1) {
            object.setStatus(1);
        }
        if(his==null){ // 新增
            object.setSchemeDetailId(manageEntityVo.getSchemeDetailId());
            object.setTaskId(manageEntityVo.getTaskId());
            object.setProceeInstanceId(manageEntityVo.getProcessInstanceId());
            spFobGmbxMapper.insert(object);
        }else { // 修改
            object.setId(his.getId());
            BeanUtils.copyProperties(object,his);
            spFobGmbxMapper.updateById(his);
            // 处理多余文件记录
            List<String> ids = new ArrayList<>();
            if((his.getFiels()!=null && his.getFiels().length()>0)){
                String temp = his.getFiels();
                String[] fieldIds = temp.split(",");
                ids =  Arrays.stream(fieldIds).collect(Collectors.toList());
            }
            spFobFileRecordService.deleteOtherFileRecor(his.getId(),ids);
        }
    }

    @Override
    public SpFobBaseBean getBaseBeanByInstanceId(String id) {
        return spFobGmbxMapper.selectOne(new LambdaQueryWrapper<SpfobUpjsfhccb>().eq(SpfobUpjsfhccb::getProceeInstanceId,id).ne(SpfobUpjsfhccb::getStatus,-2));
    }
    @Override
    public void  saveEntity(SpFobBaseBean bean){
        SpfobUpjsfhccb spFobZzgcjr = new SpfobUpjsfhccb();
        BeanUtils.copyProperties(bean,spFobZzgcjr);
        this.save(spFobZzgcjr);
    }

    @Override
    public void updateEntityById(SpFobBaseBean bean) {
        SpfobUpjsfhccb spFobZzgcjr = new SpfobUpjsfhccb();
        BeanUtils.copyProperties(bean,spFobZzgcjr);
        this.updateById(spFobZzgcjr);
    }


    @Override
    public Object getFormData(String id,Long serviceId) {
        SpfobUpjsfhccb spFobZzgcjr = null;
        if(serviceId!=null){
            spFobZzgcjr = spFobGmbxMapper.selectById(serviceId);
        }else {
            spFobZzgcjr = spFobGmbxMapper.selectOne(new LambdaQueryWrapper<SpfobUpjsfhccb>().eq(SpfobUpjsfhccb::getProceeInstanceId,id).ne(SpfobUpjsfhccb::getStatus,-2));
        }
        if(spFobZzgcjr==null){
            return null;
        }
        Map<String,Object> map = JsonUtils.jsonToMap(JsonUtils.objectToJson(spFobZzgcjr), Object.class);
        if(StringUtils.isNotBlank(spFobZzgcjr.getFiels())){
            String[] ids = spFobZzgcjr.getFiels().split(",");
            List<Long> resId = new ArrayList<>();
            for(String tempId:ids){
                if (StringUtils.isNotBlank(tempId)) {
                    resId.add(Long.parseLong(tempId));
                }
            }
            List<SpFobFileRecord> spFobFileRecordList =  spFobFileRecordService.listByIds(resId);
            map.put("fiels",spFobFileRecordList);
        }
        return map;
    }
    @Override
    public List<Long> findServieData(String processInstanceId){
        List<SpfobUpjsfhccb> spFobBaseBeans =  spFobGmbxMapper.selectList(new LambdaQueryWrapper<SpfobUpjsfhccb>().eq(SpfobUpjsfhccb::getProceeInstanceId,processInstanceId).orderByDesc(SpfobUpjsfhccb::getCreateDate));
        List<Long> list = spFobBaseBeans.stream().map(SpFobBaseBean::getId).collect(Collectors.toList());
        return list;
    }

    //创建订单，执行同步费用信息

    @Autowired
    SmShipFreightCostService smShipFreightCostService;
    @Override
    public void createCostInfo(Long id,String key) {
        SpfobUpjsfhccb spfobUpjsfhccb = this.spFobGmbxMapper.selectById(id);
        if(spfobUpjsfhccb!=null && spfobUpjsfhccb.getCostId()!=null){
            return;
        }
        SpDispatchSchemeExecute execute = dispatchSchemeExecuteService.getExceuteByInstanceId(spfobUpjsfhccb.getProceeInstanceId());
        SmShipFreightCost cost = new SmShipFreightCost();
        cost.setCostKey(key);
        cost.setDataSource("1");
        cost.setVesselName(execute.getShipName());
        cost.setVoyageNumber(execute.getVoyageNo());
        cost.setLoadingPort(execute.getExpectedLoadingPort());
        cost.setDischargePort(execute.getExpectedLoadingPort());
        cost.setProcessInstanceId(spfobUpjsfhccb.getProceeInstanceId());
        cost.setJsfhccbId(id);
        cost.setImo(execute.getImo());
        cost.setVoyageStartTime(execute.getRealityLoadingDate());
        cost.setVoyageEndTime(execute.getRealityUnloadingDate());
        List<SpFobJsfhccbItems> list = this.spFobGmbxMapper.findListByServiceId(id);
        //封装参数
        for(SpFobJsfhccbItems item:list){
            if("CharterCost".equals(item.getTableId()) && "Total".equals(item.getA1())){
                cost.setCharterCost(item.getA2());
            }else  if("ShippingAgencyCost".equals(item.getTableId()) && "Total".equals(item.getA1())){
                cost.setShippingAgencyCost(item.getA2());
            }else  if("Insurance".equals(item.getTableId()) && "Total".equals(item.getA1())){
                cost.setInsurance(item.getA2());
            }else  if("LSMGO".equals(item.getTableId()) && "Total".equals(item.getA1())){
                cost.setLsmgo(item.getA2());
            }else  if("VLSFO".equals(item.getTableId()) && "Total".equals(item.getA1())){
                cost.setVlsfo(item.getA2());
            }else  if("PositioningFee".equals(item.getTableId()) && "Total".equals(item.getA1())){
                cost.setPositioningFee(item.getA2());
            }else  if("BallastBonus".equals(item.getTableId()) && "Total".equals(item.getA1())){
                cost.setBallastBonus(item.getA2());
            }else  if("BOG".equals(item.getTableId()) && "Total price".equals(item.getA1())){
                cost.setBog(item.getA2());
            }else  if("BOG".equals(item.getTableId()) && "Estimated discharge quantity".equals(item.getA1())){
                cost.setEstimatedDischargeQuantity(item.getA2());
            }else  if("BOG".equals(item.getTableId()) && "Shipping cost".equals(item.getA1())){
                cost.setShippingCost(item.getA2());
            }
        }
        if(key.contains("FOB004")){
            cost.setCostBeforeKey("FOB004-14");
        }else{
            cost.setCostBeforeKey("FOB001-14");
        }
        SpFobBaseBean baseBean = spfobJsfhccbService.getBaseBeanByInstanceId(spfobUpjsfhccb.getProceeInstanceId());
        if(baseBean!=null){
            cost.setJsfhccbBeforeId(baseBean.getId());
        }
        Long costId = smShipFreightCostService.saveFreightCost(cost);
        spfobUpjsfhccb.setCostId(costId);
        //记录costid
        this.spFobGmbxMapper.updateById(spfobUpjsfhccb);
    }
}
